import 'dart:async';

import 'package:bike_ride/api/api_defines.dart';
import 'package:bike_ride/common/net/base_repository.dart';
import 'package:bike_ride/common/net/dio_client.dart';
import 'package:bike_ride/common/net/dio_response.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/model/login/model/login_m.dart';
import 'package:dio/dio.dart';

class LoginRepository extends BaseRepository {
  /// 手机验证码登录
  static Future<bool> mobileLoginIdl({
    CancelToken? cancelToken,
    required String mobile,
    required String code,
  }) async {
    final response = await DioClient().doPost(kAPIURLMobileLogin,
        cancelToken: cancelToken,
        data: {'platform': 1, 'code': code, 'mobile': mobile});
    if (response.statusCode == REQUEST_SUCCESS) {
      final model = LoginM.fromJson(response.data);
      AccountManager.handleLogin(model);
      return true;
    } else {
      DioClient.showError(response);
      return false;
    }
  }

  /// 发送验证码
  static Future<bool> mobileSendIdl({
    CancelToken? cancelToken,
    required String mobile,
  }) async {
    final response = await DioClient().doPost(kAPIURLMobileSend,
        cancelToken: cancelToken,
        data: {'mobile': mobile, 'randstr': 'no_tencent_check'});
    if (response.statusCode == REQUEST_SUCCESS) {
      return true;
    } else {
      DioClient.showError(response);
      return false;
    }
  }

  /// 发送邮箱
  static Future<bool> emailSendIdl({
    CancelToken? cancelToken,
    required String email,
  }) async {
    final response = await DioClient().doPost(kAPIURLEmailSend,
        cancelToken: cancelToken,
        data: {'email': email});
    if (response.statusCode == REQUEST_SUCCESS) {
      return true;
    } else {
      DioClient.showError(response);
      return false;
    }
  }

  /// 邮箱登录
  static Future<bool> emailLoginIdl({
    CancelToken? cancelToken,
    required String email,
    required String code,
  }) async {
    final response = await DioClient().doPost(kAPIURLEmailLogin,
        cancelToken: cancelToken,
        data: {'code': code, 'email': email});
    if (response.statusCode == REQUEST_SUCCESS) {
      final model = LoginM.fromJson(response.data);
      AccountManager.handleLogin(model);
      return true;
    } else {
      DioClient.showError(response);
      return false;
    }
  }

  /// 切换品牌
  static Future<LoginM?> changeBrandIdl({
    CancelToken? cancelToken,
    required String newBrandCode,
  })async{
    final response = await DioClient().doPost(kAPIURLChangeBrand,
        cancelToken: cancelToken,data: {'new_brand_code': newBrandCode});

    if(response.statusCode == REQUEST_SUCCESS){
      return LoginM.fromJson(response.data);
    }else{
      DioClient.showError(response);
      return null;
    }
  }
}
